import { getTags } from '@/api/exam/tags';
import { Input, InputRef, Select, Tag } from 'antd';
import FormItem from 'antd/es/form/FormItem';
import React, { useEffect, useRef, useState } from 'react';

interface Props {
  // data: TagsItem[];
  formRef: any;
}

const { Option } = Select;

export default function AddForm({ formRef }: Props) {
  const [tags, setTags] = useState([]);
  const [options, setOptions] = useState<any[]>([]);
  const [inputVisible, setInputVisible] = useState(false);
  const [inputValue, setInputValue] = useState('');
  const inputRef = useRef<InputRef>(null);
  const [type, setType] = useState('');
  useEffect(() => {
    getTags().then((res) => {
      setTags(res.data.map((it: any) => it.tagName));
    });
  }, []);

  useEffect(() => {
    if (formRef && options.length && ['单选题', '多选题'].includes(type)) {
      formRef.setFieldsValue({
        options
      });
    }
  }, [options]);

  useEffect(() => {
    if (inputVisible) {
      inputRef.current?.focus();
    }
  }, [inputVisible]);

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setInputValue(e.target.value);
  };

  const handleInputConfirm = () => {
    if (inputValue && options.indexOf(inputValue) === -1) {
      setOptions([...options, inputValue]);
    }
    setInputVisible(false);
    setInputValue('');
  };

  const cancelAddOption = (idx: number) => {
    const optionsCopy = options.slice();
    optionsCopy.splice(idx, 1);
    setOptions(optionsCopy);
  };

  const handleTypeChange = (text: string) => setType(text);

  return (
    <>
      <FormItem name="type" label="题型" rules={[{ required: true }]}>
        <Select placeholder="请选择题型" onChange={handleTypeChange}>
          <Option value="单选题">单选题</Option>
          <Option value="多选题">多选题</Option>
          <Option value="简答题">简答题</Option>
          <Option value="编程题">编程题</Option>
        </Select>
      </FormItem>
      <FormItem name="difficulty" label="难度" rules={[{ required: true }]}>
        <Select placeholder="请选择难度">
          <Option value="简单">简单</Option>
          <Option value="中等">中等</Option>
          <Option value="困难">困难</Option>
        </Select>
      </FormItem>
      <FormItem name="tags" label="标签" rules={[{ required: true }]}>
        <Select mode="tags" placeholder="请选择标签" tokenSeparators={[',']}>
          {tags.map((tag) => (
            <Option key={tag}>{tag}</Option>
          ))}
        </Select>
      </FormItem>
      <FormItem name="question" label="题目" rules={[{ required: true }]}>
        <Input.TextArea placeholder="请输入题目" />
      </FormItem>
      <FormItem name="description" label="题目描述">
        <Input.TextArea placeholder="请输入题目描述" />
      </FormItem>
      {['单选题', '多选题'].includes(type) && (
        <FormItem name="options" label="选项" rules={[{ required: true }]}>
          <Input style={{ display: 'none' }} />
          {options.map((it, index) => (
            <Tag closable onClose={() => cancelAddOption(index)} key={it}>
              {it}
            </Tag>
          ))}
          {inputVisible ? (
            <Input
              ref={inputRef}
              type="text"
              size="small"
              style={{
                width: 78,
                verticalAlign: 'top'
              }}
              value={inputValue}
              onChange={handleInputChange}
              onBlur={handleInputConfirm}
              onPressEnter={handleInputConfirm}
            />
          ) : (
            <Tag onClick={() => setInputVisible(true)}>+ 添加选项</Tag>
          )}
        </FormItem>
      )}
      <FormItem name="answer" label="答案" rules={[{ required: true }]}>
        {['单选题', '多选题'].includes(type) ? (
          <Select disabled={!options.length} placeholder="请选择答案" mode={type === '多选题' ? 'multiple' : undefined} allowClear>
            {options.map((answer) => (
              <Option value={answer}>{answer}</Option>
            ))}
          </Select>
        ) : (
          <Input.TextArea placeholder="请输入答案" minLength={6} />
        )}
      </FormItem>
      <FormItem name="analysis" label="解析">
        <Input.TextArea placeholder="请输入题目解析" />
      </FormItem>
    </>
  );
}
